package api

import (
	"encoding/json"
	"fmt"
	"gin_jwt/internal/domain/model"
	"gin_jwt/internal/domain/service"
	"gin_jwt/utils"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func Start() {

	r := gin.Default()

	r.GET("/login", func(c *gin.Context) {
		var username string = c.Query("username")
		var password string = c.Query("password")

		log.Println(username, password)

		sysUserService := service.NewSysUserService()
		resUser, err := sysUserService.Login(username, password)
		if err != nil {
			c.JSON(500, ErrWithData(err.Error()))
			return
		}

		// 定义过期时长
		var exiprTime int = 10

		//登录成功，生成token
		_userClaim := &model.UserClaims{
			resUser.UserID,
			resUser.Username,
		}
		jwtUtilCtx := utils.GetJwtUtil()
		//token, err := jwtUtilCtx.CreateTokenWithClaims(_userClaim, "my-app", "user-auth", time.Duration(exiprTime)*time.Second)
		token, err := jwtUtilCtx.CreateTokenWithClaims(_userClaim, "my-app", "user-auth", time.Duration(exiprTime)*time.Hour) // 小时单位
		if err != nil {
			fmt.Println("token创建失败:", err)
			return
		}
		log.Println("生成的用户JWT Token: %s\n", token)

		var parseUserClaim utils.BaseClaims
		if err := jwtUtilCtx.ValidateToken(token, &parseUserClaim); err != nil {
			log.Println("验证token失败：", err)
		}
		log.Println("解析token: ", parseUserClaim)

		// 存储到cookie
		cookieCtx := utils.GetCookieUtil().Use(c)
		cookieCtx.SetCookie(username, token)
		log.Println("获取cookie值：", cookieCtx.GetCookie(username))

		c.JSON(200, OkWithData(token))
	})

	// 浏览器会自动删除过期 cookie，你不需要手动清理
	r.GET("/delCookie", func(c *gin.Context) {
		cookieCtx := utils.GetCookieUtil().Use(c)
		cookieCtx.DelAllCookies()
		c.JSON(200, OkWithMsg("success"))
	})

	// 受保护的路由
	// 请求头中要携带参数：auth_cookie
	auth := r.Group("/")
	auth.Use(AuthMiddleware())
	{
		auth.GET("/test1", func(c *gin.Context) {
			// 获取
			currentUserId, _ := c.Get("userid")
			c.JSON(http.StatusOK, OkWithData(currentUserId))
		})

		auth.GET("/test2", func(c *gin.Context) {
			// 获取
			currentUserId, _ := c.Get("userid")
			c.JSON(http.StatusOK, OkWithData(fmt.Sprintf("当前用户id:%.0f", currentUserId)))
		})

	}

	r.Run(":60000")

}

// 验证登录状态中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求headers中获取参数：auth_cookie
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(401, ErrWithMsg("Authorization header required!"))
			c.Abort()
			return
		}

		log.Println("请求头携带的Authorization：", authHeader)

		jwtUtilCtx := utils.GetJwtUtil()
		var parseUserClaim utils.BaseClaims
		if err := jwtUtilCtx.ValidateToken(authHeader, &parseUserClaim); err != nil {
			c.JSON(500, ErrWithMsg(fmt.Sprintf("验证token失败:%s", err.Error())))
			c.Abort()
			return
		}

		jsonStr, err := json.Marshal(parseUserClaim.CustomClaims)
		if err != nil {
			c.JSON(500, ErrWithData(err.Error()))
		}
		var parseMap map[string]interface{}
		json.Unmarshal([]byte(jsonStr), &parseMap)
		log.Println("解析token: ", jsonStr)
		log.Println("当前登录的用户: ", parseMap["userid"])

		// 将用户信息存储到上下文
		c.Set("userid", parseMap["userid"])
		// 将用户信息存入上下文
		c.Next()
	}
}
